package com.github.syncrepo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;

/**
 * Utility class for file operations
 */
public class FileUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * Delete directory recursively
     */
    public static void deleteDirectory(File directory) throws IOException {
        if (directory == null || !directory.exists()) {
            return;
        }

        logger.info("Deleting directory: {}", directory.getAbsolutePath());
        
        Files.walk(directory.toPath())
                .sorted(Comparator.reverseOrder())
                .map(Path::toFile)
                .forEach(File::delete);
        
        logger.info("Directory deleted successfully");
    }

    /**
     * Create temporary directory for git operations
     */
    public static File createTempDirectory(String prefix) throws IOException {
        Path tempDir = Files.createTempDirectory(prefix);
        logger.info("Created temporary directory: {}", tempDir.toAbsolutePath());
        return tempDir.toFile();
    }

    /**
     * Ensure directory exists, create if not
     */
    public static File ensureDirectory(String path) throws IOException {
        File dir = new File(path);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new IOException("Failed to create directory: " + path);
            }
            logger.info("Created directory: {}", path);
        }
        return dir;
    }
}

